package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 查询自媒体文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findNews(WmNewsPageReqDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //获取当前登录用户
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        IPage<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        //根据文章状态查询
        lqw.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //关键字模糊查询
        lqw.like(StringUtils.isNotEmpty(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //根据频道查询
        lqw.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lqw.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //查询当前用户的文章
        lqw.eq(WmNews::getUserId, user.getId());
        //文章按照创建时间降序
        lqw.orderByDesc(WmNews::getCreatedTime);

        wmNewsPage = page(wmNewsPage, lqw);

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) wmNewsPage.getTotal());
        responseResult.setData(wmNewsPage.getRecords());
        return responseResult;
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //参数校验
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或者修改文章
        WmNews wmNews = new WmNews();
        //属性copy
        BeanUtils.copyProperties(dto, wmNews);
        //获取封面图片
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //把dto中图片类型由list转换为 String类型存入文章表
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        //封面类型 如果是自动 先设置为null 因为 数据库不允许设置-1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_AUTO_IMAGE)) {
            wmNews.setType(null);
        }
        //保存或修改文章
        saveOrUpdateWmNews(wmNews);

        //判断是否是草稿 是草稿直接返回
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿 保存文章图片和素材的关系
        //获取文章内容中的图片
        List<String> imagesUrls = getImagesByContent(dto.getContent());
        //处理文章内容图片和素材的关系
        saveNewsImagesWithMaterial(imagesUrls, wmNews.getId());

        //处理封面图片和素材的关系
        saveCoverImagesWithMaterial(dto, wmNews, imagesUrls);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //处理文章封面图片和素材的关系
    private void saveCoverImagesWithMaterial(WmNewsDto dto, WmNews wmNews, List<String> imagesUrls) {
        List<String> images = dto.getImages();
        //如果封面类型是自动
        if (dto.getType().equals(WemediaConstants.WM_NEWS_AUTO_IMAGE)) {
            //多图
            if (imagesUrls.size() >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = imagesUrls.stream().limit(3).collect(Collectors.toList());
                //单图
            } else if (imagesUrls.size() >= 1 && imagesUrls.size() < 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = imagesUrls.stream().limit(1).collect(Collectors.toList());
                //无图
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NOT_IMAGE);
            }
            //修改文章
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }
        //保存文章封面图片和素材的关系
        if (images != null && images.size() > 0) {
            saveNewsImagesInfo(imagesUrls, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);

        }
    }

    //处理文章内容图片和素材的关系
    private void saveNewsImagesWithMaterial(List<String> imagesUrls, Integer newsId) {
        //保存文章图片和素材关系到数据库
        saveNewsImagesInfo(imagesUrls, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    //保存文章图片和素材关系到数据库
    private void saveNewsImagesInfo(List<String> imagesUrls, Integer newsId, Short type) {
        if (imagesUrls != null && !imagesUrls.isEmpty()) {
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imagesUrls));
            //判断素材是否失效
            if (wmMaterials == null || wmMaterials.size() == 0) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            if (imagesUrls.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            List<Integer> idList = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(idList, newsId, type);
        }
    }

    /**
     * 获取文章内容图片url
     *
     * @param content
     * @return
     */
    private List<String> getImagesByContent(String content) {
        List<String> imagesUrls = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                imagesUrls.add(imgUrl);
            }
        }
        return imagesUrls;
    }

    //保存或者修改文章
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架

        if (wmNews.getId() == null) {
            //没有文章id  添加
            save(wmNews);
        } else {
            //有文章id 修改
            //先删除文章图片和素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //再修改
            updateById(wmNews);
        }
    }
}
